<template>
  <div>
    <div v-model="searchData" style="margin: 10px 0">
      <el-input v-model="searchData.name" style="width: 200px" placeholder="请输入课程名称"
                suffix-icon="el-icon-search"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="rest">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="addHander" v-if="user.role!=='学生'">新增 <i
          class="el-icon-circle-plus-outline"></i></el-button>
      <el-button type="danger" @click="delBatch" v-if="user.role!=='学生'">批量删除 <i class="el-icon-remove-outline"></i>
      </el-button>
      <el-button type="primary" @click="selectMore" v-if="user.role==='学生'">多选 <i
          class="el-icon-circle-plus-outline"></i></el-button>
      <el-button type="primary" @click="studentLookCourses" v-if="user.role==='学生'">查看已选课程 <i
          class="el-icon-search"></i></el-button>
    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="Id" width="40"></el-table-column>
      <el-table-column prop="name" label="课程名称" width="120"></el-table-column>
      <el-table-column prop="score" label="学分" width="120"></el-table-column>
      <el-table-column prop="times" label="课时"></el-table-column>
      <el-table-column prop="teacherName" label="教师"></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="selectCourse(scope.row.id)" v-if="user.role ==='学生'">选课 <i
              class="el-icon-reading"></i></el-button>
          <el-button type="success" @click="handleEdit(scope.row.id)" v-if="user.role!=='学生'">编辑 <i
              class="el-icon-edit"></i></el-button>
          <el-button type="danger" @click="del(scope.row.id)" v-if="user.role!=='学生'">删除 <i
              class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="新增课程信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form" label-width="80px" size="small">
        <el-form-item label="课程名称">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学分">
          <el-input v-model="form.score" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课时">
          <el-input v-model="form.times" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="教师">
          <el-select v-model="form.teacherId" placeholder="请选择" style="width: 100%">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.nickname"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改课程信息" :visible.sync="updateFormVisible" width="30%">
      <el-form :model="info" label-width="80px" size="small">
        <el-form-item label="课程名称">
          <el-input v-model="info.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学分">
          <el-input v-model="info.score" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课时">
          <el-input v-model="info.times" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="教师">
          <el-select v-model="info.teacherId" placeholder="请选择" style="width: 100%">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.nickname"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="课程信息" :visible.sync="lookVisible" width="50%">
      <el-table :data="courses" border stripe>
        <el-table-column prop="name" label="课程名称"></el-table-column>
        <el-table-column prop="score" label="学分"></el-table-column>
        <el-table-column prop="teacherId" label="教师"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Course",
  data() {
    return {
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      multipleSelection: [],
      searchData: {
        name: '',
      },
      form: {},
      info: {},
      tableData: [],
      headerBg: 'headerBg',
      current: 0,
      total: 0,
      pageSize: 5,
      dialogFormVisible: false,
      updateFormVisible: false,
      lookVisible: false,
      options: [],
      courses: []
    }
  },
  created() {
    this.load()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection.map(v => v.id))
    },
    //查看已选
    studentLookCourses () {
      this.lookVisible = true
      this.request.get("/course/courses/" + this.user.id).then(res => {
        if (res.code === 200) {
          this.courses = res.data
        }
      })
    },
    //选课
    selectCourse(courseId) {
      this.request.post("/course/save/" + courseId + "/" + this.user.id).then(res => {
        if (res.code === 200) {
          this.$message.success("选课成功")
        }
      })
    },
    //多选课
    selectMore() {
      let ids = this.multipleSelection.map(v => v.id)  //[1,2,3]
      this.$confirm('选择这些课程吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.post("/course/save/batch/" + this.user.id + "/" + ids).then(resp => {
          console.log(1112233)
          console.log(ids)
          console.log(resp)
          if (resp.code === 200) {
            this.load()
            this.$message({
              type: 'success',
              message: '选课成功!',
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消选课'
        });
      });

    },

    delBatch() {
      let ids = this.multipleSelection.map(v => v.id)  //[1,2,3]
      this.$confirm('此操作将删除这些课程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/course/delete/batch/" + ids).then(resp => {
          if (resp.data) {
            this.load()
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    del(id) {
      this.$confirm('此操作将永久删除课程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/course/delete/" + id).then(resp => {
          if (resp.data) {
            this.load()
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addHander() {
      this.dialogFormVisible = true
      this.form = {}

      //获得角色下拉的选项
      this.request.get("/user/teacher").then(res => {
        console.log(res)
        this.options = res.data
      })
    },

    rest() { //重置搜索栏
      this.searchData.name = ''
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log("每页条数: " + pageSize)
      this.pageSize = pageSize;
      this.load()
    },
    handleCurrentChange(current) {
      console.log("当前页码: " + current)
      this.current = current;
      this.load()
    },
    collapse() {  // 点击收缩按钮触发
      this.isCollapse = !this.isCollapse
      if (this.isCollapse) {  // 收缩
        this.sideWidth = 64
        this.collapseBtnClass = 'el-icon-s-unfold'
        this.logoTextShow = false
      } else {   // 展开
        this.sideWidth = 200
        this.collapseBtnClass = 'el-icon-s-fold'
        this.logoTextShow = true
      }
    },
    load() {
      this.request.get("/course/page", {
            params: {
              current: this.current,
              pageSize: this.pageSize,
              name: this.searchData.name,
            }
          }
      ).then(resp => {
        console.log(resp)
        this.tableData = resp.data.records
        this.total = resp.data.total
      })
    },
    save() {//新增用户
      this.request.post("/course/save", this.form).then(resp => {
        console.log(resp)
        if (resp.data) {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
          this.load()
        }
      })
    },
    //编辑
    handleEdit(id) {
      console.log(id)
      this.request.get("/course/" + id).then(resp => {
        console.log("根据id查到的数据")
        console.log(resp)
        this.info = resp.data
      })
      //获得角色下拉的选项
      this.request.get("/user/teacher").then(res => {
        console.log(res)
        this.options = res.data
      })
      this.updateFormVisible = true
    },
    //更新数据
    update() {
      this.request.put("/course/update/", this.info).then(resp => {
        console.log(this.info)
        console.log(resp)
        if (resp.data) {
          this.$message.success("更新成功")
          this.updateFormVisible = false
          this.load()
        } else {
          this.$message.error("更新失败")
        }
      })
    },
  }
}
</script>

<style>
.headerBg {
  background: #eee !important;
}
</style>